import { getUserAgentLanguage } from '@/utils/index';

function getValidLang(lang) {
  if (typeof lang !== 'string') return '';
  if (/zh/i.test(lang)) return 'zh';
  if (/km/i.test(lang)) return 'km';
  if (/en/i.test(lang)) return 'km';
  return '';
}

function getPreferUserAgentLang(req) {
  const lang = getUserAgentLanguage(req);
  if (typeof lang !== 'string') return '';
  const [prefer] = lang.split(',');
  return prefer;
}

function safeGetQueryLang(lang) {
  if (Array.isArray(lang)) {
    return safeGetQueryLang(lang[0]);
  }
  if (typeof lang == 'string') return lang;
  return '';
}

export default function({
  isHMR,
  app,
  store,
  route,
  params,
  error,
  redirect,
  req,
  cookies
}) {
  if (isHMR) return;

  let locale = getValidLang(params.lang);
  if (!locale) locale = getValidLang(safeGetQueryLang(route.query.lan));
  if (!locale) locale = getValidLang(getPreferUserAgentLang(req));
  if (!locale) locale = getValidLang(app.i18n.fallbackLocale);
  if (!locale) locale = 'km';

  // Set locale
  store.commit('SET_LANG', locale);
  app.i18n.locale = store.state.locale;
}
